import Taro from '@tarojs/taro'
import { Text, View } from '@tarojs/components'
import React, { useCallback, useEffect, useMemo, useState } from 'react'
import { date } from '@pier88health/p8h-common'
import i18n from '@I18N'
import api from '@API'
import { Analytic_Type } from '@CONSTANTS/analytic'
import Echarts from '@COMPONENTS/PainLog/Echarts'
import { DaySummaryITF, PainLogDaySummaryITF } from '@INTERFACES/PainLog'
import { showToast } from '@UTILS/common'
import Images from '@ASSET/Images'
import ReportCard from '@SUBPACKAGES/log/component/ReportCard'
import style from './PainCharts.module.scss'

interface TabsProps {
  tabs: string[]
  activeIndex: number
  onClickItem: (index: number) => void
}

const GRID = {
  top: 10,
  left: 0,
  bottom: 0,
  right: 16,
  containLabel: true
}

const Tabs: React.FC<TabsProps> = ({ tabs, activeIndex, onClickItem }) => (
  <View className={style.tabBar}>
    {tabs.map((item, index) => (
      <View
        key={item}
        onClick={() => {
          onClickItem(index)
        }}
        className={`${style.tabBarItem} ${index === activeIndex ? style.activeTab : ''}`}
      >
        <Text className={style.tabBarItemText}>{item}</Text>
        <View className={style.indicate} />
      </View>
    ))}
  </View>
)

const TABS_CHART_THEMES = [{
  color: '#FF8F09',
  shadowColor: 'rgba(227, 130, 15, 0.2)',
  name: '疼痛程度',
  unit: '单位：程度/日期'
}, {
  color: '#47C690',
  shadowColor: 'rgba(71, 198, 144, 0.2)',
  name: '发作次数',
  unit: '单位：次数/日期'
}, {
  color: '#07BFE3',
  shadowColor: 'rgba(7, 191, 227, 0.2)',
  name: '持续时间',
  unit: '单位：小时/日期'
}]

function getDisplayDate(time = '') {
  const curDate = new Date(time.replace(/-/g, '/'))
  const dateStr = curDate.getDate()
  const monthStr = curDate.getMonth() + 1
  return `${monthStr}.${dateStr}`
}

const initEmptyDaySummary = (day: number) => new Array(day).fill(0).reduce((preArray, currentValue, currentIndex) => {
  const nowDate = new Date()
  const aimDate = new Date(nowDate.setDate(nowDate.getDate() - currentIndex)).getTime()
  const item = {
    Count: 0,
    DateBucket: date.dateFormat(aimDate, 'yyyy-MM-dd'),
    Frequency: 0,
    OverallRating: 0,
    TotalTime: 0
  }
  preArray.unshift(item)
  return preArray
}, [])

const handleData = (daySummary: DaySummaryITF[]) => {
  const intensity: Array<number| null> = []
  const frequency: Array<number| null> = []
  const totalTime: Array<number| null> = []
  const xAxisData: string[] = []
  const dateBucketsData: string[] = []
  let intensityCount = 0
  let frequencyCount = 0
  let totalTimeCount = 0
  daySummary.forEach(item => {
    const {
      OverallRating, Frequency, TotalTime, DateBucket, EmptyData
    } = item || {}
    const dataKey = getDisplayDate(DateBucket)
    const time = Math.round(TotalTime * 10) / 10
    intensity.push(EmptyData ? null : OverallRating)
    frequency.push(EmptyData ? null : Frequency)
    totalTime.push(EmptyData ? null : time)
    dateBucketsData.push(DateBucket)
    xAxisData.push(dataKey)
    if (!EmptyData) {
      intensityCount += 1
      frequencyCount += 1
      totalTimeCount += 1
    }
  })
  return {
    intensity: { data: intensity, isOne: intensityCount === 1 },
    frequency: { data: frequency, isOne: frequencyCount === 1 },
    totalTime: { data: totalTime, isOne: totalTimeCount === 1 },
    xAxisData,
    dateBucketsData
  }
}
interface Props {
  pId?: string
  uniqueKey: string
  bucket: string
  position: string
}

const PainCharts: React.FC<Props> = ({ pId, uniqueKey, bucket, position }) => {
  const [chartTypeIndex, setChartTypeIndex] = useState(0)
  const [key, setKey] = useState(new Date().getTime())
  const [data, setData] = useState<Array<any>>()
  const [xAxis, setXData] = useState<Array<string>>([])

  const fetchData = useCallback(async () => {
    try {
      let result = {} as PainLogDaySummaryITF
      if (!pId) {
        result.DaySummary = initEmptyDaySummary(6)
      } else {
        result = await api.getPainLogDaySummaryByDate({ pId, monthBucket: bucket, position })
      }
      const { DaySummary } = result
      const { intensity, frequency, totalTime, xAxisData } = handleData(DaySummary)
      setData([intensity, frequency, totalTime])
      setXData(xAxisData)
    } catch (error) {
      showToast(error)
    }
  }, [bucket, pId, position])

  const tabs = useMemo(() => [i18n.patient.intensity(), i18n.patient.frequency_tab(), i18n.patient.duration()], [])

  const onTabChange = useCallback(index => {
    setChartTypeIndex(index)
    Taro.tracker.trackEvent(Analytic_Type.tap_pain_chart.eventId, { painChartType: tabs[index] })
  }, [tabs])
  useEffect(() => {
    if (uniqueKey) {
      setKey(new Date().getTime())
    }
  }, [uniqueKey])
  useEffect(() => {
    fetchData()
  }, [fetchData])
  const chartTheme = useMemo(() => TABS_CHART_THEMES[chartTypeIndex], [chartTypeIndex])

  if (!data) return null
  const chartData = data[chartTypeIndex]

  return (
    <ReportCard icon={Images.pain_log.iconPainTrends} title={i18n.patient.pain_trend()}>
      <View className={style.container}>
        <Tabs
          tabs={tabs}
          activeIndex={chartTypeIndex}
          onClickItem={onTabChange}
        />
        <Text className={style.unit}>
          {chartTheme.unit}
        </Text>
        <Echarts
          showId={key}
          key={`${key}`}
          chartTheme={chartTheme}
          data={chartData.data}
          width={311}
          type={chartData.isOne ? 'scatter' : 'line'}
          symbol={chartData.isOne ? 'circle' : 'none'}
          smooth={false}
          connectNulls
          grid={GRID}
          xAxisData={xAxis}
          language="zh"
        />
      </View>
    </ReportCard>
  )
}

export default PainCharts
